const fs = window.require("fs");
const { dialog } = require("electron").remote;
const os = require("os");
const dataPath = `C:/Users/${
  os.userInfo().username
}/AppData/Roaming/easyWebsite/developPageImage`;

function uploadImage(jud) {
  let imgBufferList = [];
  let path;

  //选择图片
  path = dialog.showOpenDialogSync({
    filters: [{ name: "Images", extensions: ["jpg", "png", "gif", "jpeg"] }],
    properties: jud ? ["multiSelections"] : [],
  });

  if (path) {
    //创建目录
    try {
      fs.mkdirSync(dataPath, { recursive: true });
    } catch (error) {
      console.error(error);
      return error;
    }

    //图片复制
    path.forEach((item) => {
      try {
        let data = fs.readFileSync(item);
        let dirname = `${dataPath}/${new Date().getTime()}.${
          item
            .split("\\")
            .reverse()[0]
            .split(".")[1]
        }`;
        fs.writeFileSync(dirname, data);
        imgBufferList.push({ data, src: dirname });
      } catch (error) {
        console.error(error);
        return error;
      }
    });
    return imgBufferList;
  }

  return undefined;
}

function deleteImage(imgList) {
  let list = [];
  let filesList;

  //清洗数据
  for (const key in imgList) {
    if (Object.hasOwnProperty.call(imgList, key)) {
      list.push(imgList[key].src);
    }
  }

  try {
    filesList = fs.readdirSync(dataPath);
    //删除多余图片
    filesList.forEach((item) => {
      let imgPath = dataPath + "/" + item;
      if (!list.includes(imgPath)) {
        fs.unlinkSync(imgPath);
      }
    });
  } catch (error) {
    console.error(error);
  }
}

//读取图片列表
function imageList() {
  let list = fs.readdirSync(dataPath);
  return list.map((item) => {
    let path = dataPath + "/" + item;
    return { path, buffer: fs.readFileSync(path) };
  });
}

module.exports = {
  uploadImage,
  deleteImage,
  imageList,
};
